<template>
  <header>
    <div class="search-return" @click="goBack">
      <i class="iconfont icon-fanhui1"></i>
    </div>
    <div class="search-main">
      <i class="iconfont icon-sousuo"></i>
      <form action="" onsubmit="return false" @keyup.enter="goSearchList">
        <input
          type="text"
          placeholder="搜索您喜欢的产品"
          v-model="searchvalue"
        />
      </form>
    </div>
    <div class="search-btn" @click="goSearchList">搜索</div>
  </header>
</template>

<script>
export default {
  name: "Header",
  data() {
    return {
      searchvalue: this.$route.query.key || "",
      searchArr: [],
    };
  },
  created() {
    // console.log(this.$route.query);
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    goSearchList() {
      //如果搜索的关键字没有 直接返回
      if (!this.searchvalue) return;
      if (!localStorage.getItem("searchList")) {
        //没有
        localStorage.setItem("searchList", "[]");
      } else {
        //之前有
        this.searchArr = JSON.parse(localStorage.getItem("searchList"));
      }
      //增加数据
      this.searchArr.unshift(this.searchvalue);
      //去重
      let newArr = new Set(this.searchArr);
      // console.log(...newArr);
      //给本地存储赋值
      localStorage.setItem("searchList", JSON.stringify(Array.from(newArr)));
      // console.log(this.searchvalue);
      if (this.searchvalue === this.$route.query.key) return;
      this.$router.push({
        name: "list",
      });
    },
  },
};
</script>

<style lang="less" scoped>
header {
  display: flex;
  justify-content: space-around;
  justify-items: center;
  align-items: center;
  width: 100%;
  height: 55px;
  background-color: #b0352f;
  color: #fff;
}
.search-return {
  padding: 0 10px;
  i {
    font-size: 25px;
  }
}
.search-main {
  display: flex;
  width: 255px;
  height: 35px;
  line-height: 30px;
  background-color: #fff;
  border-radius: 15px;
  font-size: 16px;
  i {
    color: #000;
    padding: 0 15px;
  }
}
.search-btn {
  padding: 0 10px;
  font-size: 19px;
}
</style>